package com.wee.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bigtotoro.util.DeviceUtil;
import com.bigtotoro.util.SharedPreferencesUtil;
import com.bigtotoro.util.StringUtil;
import com.bigtotoro.widgets.AppProgressBar;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.wee.aircoach_user.Constant;
import com.wee.aircoach_user.MainActivity;
import com.wee.aircoach_user.R;
import com.wee.aircoach_user.RegisterActivity;
import com.wee.entity.MD5Util;
import com.wee.entity.Tools;
import com.wee.entity.UserRegister;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

import de.hdodenhof.circleimageview.CircleImageView;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * Created by xiaobing on 15/8/10.
 */
public class
        FragRegister2 extends Fragment implements View.OnClickListener {
    private String tag = getClass().getName();
    private View rootView;//缓存Fragment view
    private RegisterActivity activity;

    private EditText editName, eidtBirthday;
    private CheckBox agreement_check;
    private CircleImageView imagePhoto;

    private TextView txtBirthdayPicker,editHeight, editWeight;
    private String gender = "male";//默认男
    private String dateStr = "1987-01-01";
    private DatePickerDialog datePickerDialog;

    private OSS oss;
    String  file_name;
    private static final int PHOTO_REQUEST = 1;
    private static final int CAMERA_REQUEST = 2;
    private static final int PHOTO_CLIP = 3;

    private String hei;
    private String wei;
    private Boolean  neng=false;
    private String imgPahth="";
    private String imgURL="http://image-test.aircoach.cn/image/";
    private  int random;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = (RegisterActivity)getActivity();
        Log.d(tag, "onCreate");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Log.d(tag, "onCreateView");
        random=new Random().nextInt(9999);
        if(rootView==null){
            rootView=inflater.inflate(R.layout.register, null);
            initView();
        }
        //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        return rootView;
    }

    private void initView() {
        oss = new OSSClient(getActivity(), Tools.ENDPOINT,Tools.credetialProvider);
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次

        rootView.findViewById(R.id.back).setOnClickListener(this);
        rootView.findViewById(R.id.btn_next_2).setOnClickListener(this);
        txtBirthdayPicker = (TextView)rootView.findViewById(R.id.birthday);
        txtBirthdayPicker.setOnClickListener(this);
        editName = (EditText)rootView.findViewById(R.id.name);
        editHeight = (TextView)rootView.findViewById(R.id.height);
        editHeight.setOnClickListener(this);
        editWeight = (TextView)rootView.findViewById(R.id.weight);
        editWeight.setOnClickListener(this);
      /*  rootView.findViewById(R.id.agreement).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(activity, CopyRightActivity.class));
            }
        });*/
        agreement_check = (CheckBox)rootView.findViewById(R.id.agreement_check);
        agreement_check.setChecked(true);
        imagePhoto = (CircleImageView)rootView.findViewById(R.id.avatar);
        imagePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSystemPickerDialog();
            }
        });
        ((RadioGroup)rootView.findViewById(R.id.sex_group)).setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(checkedId == R.id.sex_0){
                    gender = "male";
                }else if(checkedId == R.id.sex_1){
                    gender = "female";
                }
            }
        });
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        Log.d(tag, "onAttach");
    }

    @Override
    public void onDetach() {
        super.onDetach();
        Log.d(tag, "onDetach");
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btn_next_2){
            if (imgPahth==null){
                Toast.makeText(getActivity(),"eorr",Toast.LENGTH_LONG).show();
                return;
            }else{
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        asyncPutObjectFromLocalFile();
                    }

                }).start();
                register();
            }
        }else if(v.getId() == R.id.back){
            activity.viewPager.setCurrentItem(0);
        }else if(v.getId() == R.id.birthday){
            if(datePickerDialog==null){
                datePickerDialog = new DatePickerDialog(activity, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

                        dateStr = formatDate(year, monthOfYear, dayOfMonth);
                        txtBirthdayPicker.setText(dateStr);
                    }
                }, 1987,0,1);
                dateStr = "1987-01-01";
            }
            datePickerDialog.show();
        }else if(v.getId() == R.id.height){
            NumberPicker mPicker = new NumberPicker(getActivity());
            mPicker.setMinValue(145);
            mPicker.setMaxValue(190);
            mPicker.setValue(165);
            mPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {

                @Override
                public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                    // TODO Auto-generated method stub
                    editHeight.setText(String.valueOf(newVal));

                    /* number = Integer.parseInt(String.valueOf(newVal));

                    System.out.println("AAAAAAAAA" + number);*/
                    Height(String.valueOf(newVal));
                    int number = Integer.parseInt(String.valueOf(newVal));

                }
            });

            AlertDialog mAlertDialog = new AlertDialog.Builder(getActivity())
                    .setTitle("身高(Cm)").setView(mPicker).setPositiveButton("ok",null).create();
            mAlertDialog.show();


        }else if(v.getId() == R.id.weight){
            NumberPicker mPicker1 = new NumberPicker(getActivity());
            mPicker1.setMinValue(45);
            mPicker1.setMaxValue(110);
            mPicker1.setValue(50);
            mPicker1.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {

                @Override
                public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
                    // TODO Auto-generated method stub
                    editWeight.setText(String.valueOf(newVal));

                 /*        number = Integer.parseInt(String.valueOf(newVal));

                    System.out.println("AAAAAAAAA" + number);*/
                    Weight(String.valueOf(newVal));
                    int number1 = Integer.parseInt(String.valueOf(newVal));

                    System.out.println("AAAAAAABB" + number1);
                }
            });

            AlertDialog mAlertDialog = new AlertDialog.Builder(getActivity())
                    .setTitle("体重(Kg)").setView(mPicker1).setPositiveButton("ok",null).create();
            mAlertDialog.show();


        }

    }
    private void Height(String value){
        hei = value;
    }
    private void Weight(String value){
        wei=value;
    }
    /***************************************************************************************************************/
    public void asyncPutObjectFromLocalFile() {
        // TODO Auto-generated method stub
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(Tools.testBucket, "image/"+file_name, imgPahth);

        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });

        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");

                /**如果成功上传服务器 那就能提交表单**/
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常

                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
            }
        });

        // task.cancel(); // 可以取消任务

        // task.waitUntilFinished(); // 可以等待直到任务完成

    }


    /***************************************************************************************************************/

    private void register(){
      /*  if(!agreement_check.isChecked()){
            Toast.makeText(activity, "请勾选授权协议", Toast.LENGTH_SHORT).show();
            return;
        }*/
        String  height;
        String weight;
        String name = editName.getText().toString();
       if(hei!=null){
        height  = hei.toString().trim();
       }else{
           height="165";
       }
        if(wei!=null){
            weight  = wei.toString().trim();
        }else{
            weight="50";
        }

        if(name.length()==0){
            Toast.makeText(activity, "姓名不能为空",Toast.LENGTH_SHORT).show();
            return;
        }
        if(height.length()==0 || !StringUtil.isInt(height)){
            Toast.makeText(activity, "身高不能为空且为数字",Toast.LENGTH_SHORT).show();
            return;
        }
        if(weight.length()==0 || !StringUtil.isInt(weight)){
            Toast.makeText(activity, "体重不能为空且为数字",Toast.LENGTH_SHORT).show();
            return;
        }
        if(dateStr.length()==0){
            Toast.makeText(activity, "请选择生日",Toast.LENGTH_SHORT).show();
            return;
        }

        if(file_name== null){
            Toast.makeText(activity, "请选择头像",Toast.LENGTH_SHORT).show();
            return;
        }
        int exact=  SharedPreferencesUtil.getInt(getActivity(), Constant.USERTIME);
        RequestParams params = new RequestParams();
        AppProgressBar.checkAndCreateProgressBar(getActivity());
       params.addBodyParameter("uuid", (DeviceUtil.getUUID(activity)+5));
        params.addBodyParameter("figure",imgURL+file_name);
        params.addBodyParameter("token", ""+ MD5Util.md5(exact));
        params.addBodyParameter("name", name);
        params.addBodyParameter("gender", gender);
        params.addBodyParameter("birthday", dateStr);
        params.addBodyParameter("weight", weight);
        params.addBodyParameter("height", height);
        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST,
                Constant.USER_REGISTER,
                params,
                new RequestCallBack<String>() {
                    @Override
                    public void onStart() {

                    }
                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {

                    }
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        String str = responseInfo.result;

                           Gson gs=new Gson();
                           JsonObject jo=gs.fromJson(str, JsonObject.class);
                           JsonElement je=jo.get("status");
                           String status = je.getAsString();
                        if("ok".equals(status)){
                            JsonObject object = jo.getAsJsonObject("data");
                            UserRegister list1 = gs.fromJson(object, UserRegister.class);
                            int userid = list1.getId();
                            String bmi=list1.getBmi().getBmi().toString();
                            SharedPreferencesUtil.setInt(activity, Constant.USERID, userid);
                            SharedPreferencesUtil.set(activity, Constant.BMI, bmi);
                        //    Toast.makeText(activity, "ss"+userid,Toast.LENGTH_SHORT).show();
                            Intent intent =new Intent(getActivity(), MainActivity.class);
                            intent.putExtra("first", "first");
                            startActivity(intent);
                            activity.finish();
                            AppProgressBar.closeProgressBar();
                       }else{
                            Toast.makeText(activity, "注册失败",Toast.LENGTH_SHORT).show();
                            AppProgressBar.closeProgressBar();
                        }
                    }
                    @Override
                    public void onFailure(HttpException error, String msg) {
                        AppProgressBar.closeProgressBar();
                    }
                });
    }

    private static String formatDate(int year, int month, int day) {

        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(0);
        cal.set(year, month, day);
        Date date = cal.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }


    //拾取照片
    private void showSystemPickerDialog(){
        Intent intent = new Intent(getActivity(), MultiImageSelectorActivity.class);
// 是否显示调用相机拍照
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SHOW_CAMERA, true);
// 最大图片选择数量
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_COUNT, 1);
// 设置模式 (支持 单选/MultiImageSelectorActivity.MODE_SINGLE 或者 多选/M ultiImageSelectorActivity.MODE_MULTI)
        intent.putExtra(MultiImageSelectorActivity.EXTRA_SELECT_MODE, MultiImageSelectorActivity.MODE_SINGLE);
// 默认选择图片,回填选项(支持String ArrayList)
        //intent.putStringArrayListExtra(MultiImageSelectorActivity.EXTRA_DEFAULT_SELECTED_LIST, defaultDataArray);
        startActivityForResult(intent, 1);
    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == getActivity().RESULT_OK){
            List<String> path = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            if(path != null && path.size()>0){
                DisplayImageOptions options = new DisplayImageOptions.Builder()
                        .showStubImage(R.drawable.coach_no)
                        .showImageForEmptyUri(R.drawable.coach_no)
                        .cacheInMemory()
                        .cacheOnDisc()
                        .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
                        .build();
                com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage("file://" + path.get(0), imagePhoto, options);
                try{
                    String about_path= path.get(0);
               //     path.clear();
                    Bitmap bitmap=revitionImageSize(about_path);
                    String url= Environment
                            .getExternalStorageDirectory().getAbsolutePath()
                            + "/ImgAirCoach";
                    String url1= url+"/uu_user_img_"+(DeviceUtil.getUUID(getActivity())+5)+random+".jpg";
                    File f=new File(url);
                    if(!f.exists()){
                        try {
                            //按照指定的路径创建文件夹
                            f.mkdirs();
                        } catch (Exception e) {
                            // TODO: handle exception
                        }
                    }
                    saveBitmap(getActivity(), bitmap, url1);
                }catch (Exception r){
                    Toast.makeText(getActivity(),"系统相机异常",Toast.LENGTH_SHORT).show();
                }
            }

        }
    }
    public static Bitmap revitionImageSize(String path){
        try{
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(
                    new File(path)));
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(in, null, options);
            in.close();
            int i = 0;
            Bitmap bitmap = null;
            while (true) {
                if ((options.outWidth >> i <= 1000)
                        && (options.outHeight >> i <= 1000)) {
                    in = new BufferedInputStream(
                            new FileInputStream(new File(path)));
                    options.inSampleSize = (int) Math.pow(2.0D, i);
                    options.inJustDecodeBounds = false;
                    bitmap = BitmapFactory.decodeStream(in, null, options);
                    break;
                }
                i += 1;
            }
            return bitmap;
        }catch (IOException e){
            e.printStackTrace();
        }
        return null;

    }
    public  void saveBitmap(Context context, Bitmap bm, String path) {
        Log.e("", "保存图片");
        try {
            File f = new File(path);
            file_name=f.getName();
            imgPahth=f.getPath();
            if (f.exists()) {
                f.delete();
            }
            FileOutputStream out = new FileOutputStream(f);
            if (bm != null) {
                bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
            }
            out.flush();
            out.close();
            Log.e("", "已经保存");
			/*
			 * if(bm != null){ if(!bm.isRecycled()){//回收图片所站的内存 bm.recycle();
			 * System.gc();//提醒系统及时回收 } }
			 */

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
